#include"UdpClient.hpp"
#include<sys/types.h>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"Common.hpp"


// 客户端要拿到服务端的ip和port
int main(int argc,char*argv[])
{
	if(argc != 3)
	{
		std::cerr << "Usage: " << argv[0] << "serverip serverport" << std::endl;
		exit(USAGE_ERR);
	}
	std::string serverip = argv[1];
	uint16_t serverport = std::stoi(argv[2]);

	// 1.创建套接字
	int sockfd = ::socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd < 0)
	{
		std::cerr << "socket error" << std::endl;
		exit(SOCKET_ERR); 
	}

	// 1.1 填充server信息
	struct sockaddr_in server;
	memset(&server,0,sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons(serverport);
	server.sin_addr.s_addr = ::inet_addr(serverip.c_str()); // 设置服务器IP地址
	// inet_addr 把点分十进制的IP字符串转成网络字节序的32位整数
	

	// 2.
	while(1)
	{
		std::cout << "please enter:";
		std::string message;
		std::getline(std::cin,message);

		// client必须要有自己的ip和端口，但是客户端不需要自己显式的调用bind
		// 而是，客户端首次sendto消息的时候，由OS自动进行bind

		int n = ::sendto(sockfd,message.c_str(),message.size(),0,CONV(&server),sizeof(server));
		(void)n;

		struct sockaddr_in temp;
		socklen_t len = sizeof(temp);
		char buffer[1024];
		n = ::recvfrom(sockfd,buffer,sizeof(buffer)-1,0,CONV(&temp),&len);
		if(n > 0)
		{
			buffer[n] = 0;
			std::cout << buffer << std::endl;
		}

	
	}

	return 0;
}